import { Component, OnDestroy, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { from, Subscription } from 'rxjs';
import { map, reduce } from 'rxjs/operators';
import { ApiConfig } from './../../../../../environments/environment';
import { CreateFolderComponent } from './views/create-folder/create-folder.component';
import { UploadFileComponent } from './views/upload-file/upload-file.component';
import {MelonNamesVoView} from "../../../graphql/nars/names/melon_names/model/names_service.model";
import {NamesService} from "../../../graphql/nars/names/melon_names/service/names_service.service";

@Component({
  selector: 'app-names',
  templateUrl: './names.component.html',
  styleUrls: ['./names.component.scss']
})
export class NamesComponent implements OnInit, OnDestroy {

  paths: MelonNamesVoView[] = [];
  curPath = '/';
  names!: MelonNamesVoView[];

  checkAll = false;

  loading = false;

  subs!: Subscription;

  root = ApiConfig.root.url;

  constructor(
    private namesService: NamesService,
    private modal: NzModalService,
    private message: NzMessageService) {

  }
  ngOnDestroy(): void {
    this.subs.unsubscribe();
  }

  ngOnInit(): void {
    this.loading = true;
    this.namesService.dir({
      path: this.curPath
      , first: 10000
      , offset: 0
      , filter: {}
    }).toPromise().then(res => {
        from(res?.data?.namesService_dir?.edges!).pipe(map(n=>n.node),reduce((acc,item,idx)=>{
          acc.push(item);
          return acc;
        }
          , new Array<MelonNamesVoView>())).subscribe({
            next: res => this.names = res
          });
        this.loading = false;
      }
    );
  }

  dir():void{
    this.namesService.dir({ path: this.curPath, first: 10000, offset: 0, filter: {} }).toPromise().then(res=>{
      from(res?.data?.namesService_dir?.edges!).pipe(map(n=>n.node),reduce((acc,item,idx)=>{
        acc.push(item);
        return acc;
      }
      ,new Array<MelonNamesVoView>())).subscribe({
        next:res=>this.names=res
      });
      this.loading = false;
    });
  }

  createFolder(): void {
    this.modal.create({
      nzTitle: '输入目录名称'
      , nzContent: CreateFolderComponent
      , nzOnOk: dia => {
        let path = this.curPath;
        if (path === '/') {
          path = dia.name.startsWith('/') ? dia.name : path + dia.name;
        } else {
          path = dia.name.startsWith('/') ? path + dia.name : path + '/' + dia.name;
        }
        this.namesService.mkdir({
          path
        }).toPromise().then(res => {
          if (res?.data?.namesService_mkdir.status) {
            this.message.success('创建目录成功');
            this.loading = true;
            this.dir();
          } else {
            this.message.error('创建目录失败')
          }
        })
      }
    });
  }

  childrenFolder(names: MelonNamesVoView): void {
    this.loading = true;
    this.curPath = names.path!;
    this.dir();
    this.paths.push(names);
  }

  parentPath(): void {
    this.paths.pop();
    const parentNames = this.paths[this.paths.length - 1];
    const path = parentNames ? parentNames.path : '/';
    this.loading = true;

    this.curPath = path!;
    this.dir();
  }

  toPath(level: number): void {
    this.paths.splice(level, this.paths.length - level);
    const parentNames = this.paths[this.paths.length - 1];
    const path = parentNames ? parentNames.path : '/';
    this.loading = true;
    this.curPath = path!;
    this.dir();
  }

  toUpload(): void {
    this.modal.create({
      nzTitle: '上传文件',
      nzContent: UploadFileComponent,
      nzComponentParams: {
        params: {
          path: this.curPath
        }
      },
      nzOnOk: res => {
        this.loading = true;
        this.dir();
      }
    });
  }

  encodeURI(path: string): string {
    return encodeURIComponent(path);
  }

  removePath(names: MelonNamesVoView): void {
    this.namesService.removePath({
      paths: [names.path!]
    }).toPromise().then(res => {
      if (res?.data?.namesService_removePath.status) {
        this.message.success('删除成功');
        this.dir();
      }else{
        this.message.error('删除失败');
      }
    });
  }
}
